package it.slkfarmserver.servers;

import it.slkfarmserver.bean.Farmer;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Logger;
import org.json.*;


import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;


public class RegistrationServer implements Runnable
{
	private ServerSocket srvSocket;
	private Connection connection;
	private String address, user, password;
	private Logger logger;
	private Socket socket;
	private Statement statement;
	// JSON Node names
		private static final String TAG_ID = "UserID";
		private static final String TAG_ALTITUDE = "Altitude";
		private static final String TAG_LATITUDE = "Latitude";
		private static final String TAG_LONGITUDE = "Longitude";
		private static final String TAG_ALTITUDE_STR = "Altitude_STR";
		private static final String TAG_LATITUDE_STR = "Latitude_STR";
		private static final String TAG_LONGITUDE_STR = "Longitude_STR";
	
	public RegistrationServer(int port, String dbAddress, String dbUser, String dbPassword) throws IOException
	{
		srvSocket = new ServerSocket(port);
		address = dbAddress;
		user = dbUser;
		password = dbPassword;
		logger = Logger.getLogger("global");
	}

	@Override
	public void run() 
	{
		logger.info("Socket istanziato, attendo connessioni");
		while(true)
		{
			try 
			{
				socket = srvSocket.accept();
				logger.info("Accettata nuova connessione");
				
				ObjectInputStream inStream = new ObjectInputStream (socket.getInputStream());
				String result = (String)inStream.readObject();
				
				JSONObject json = new JSONObject(result);
				
				logger.info("Pacchetto ricevuto" + json.toString());
				
				// Storing each json item in variable
				String id = json.getString(TAG_ID);
				String altitude = json.getString(TAG_ALTITUDE);
				if(altitude==null)
					altitude = json.getString(TAG_ALTITUDE_STR);
				String latitude = json.getString(TAG_LATITUDE);
				if(latitude==null)
					latitude = json.getString(TAG_LATITUDE_STR);
				String longitude = json.getString(TAG_LONGITUDE);
				if(longitude==null)
					longitude = json.getString(TAG_LONGITUDE_STR);
				
				//connection to DB
				connection = java.sql.DriverManager.getConnection(address,user,password);
				statement = connection.createStatement();
				logger.info("Connessione al database effettuata");
				statement.executeUpdate("INSERT INTO farmer VALUES('"+id+"','"+latitude+"','"+longitude+"','"+altitude+"')");
				logger.info("Memorizzato nel database");	
				
				/*
				 *OLD VERSION DID WITH GSON OBJECT
				gsonObject = new Gson();
				farmer = gsonObject.fromJson(result, Farmer.class);
				logger.info("Pacchetto convertito");
				connection = java.sql.DriverManager.getConnection(address,user,password);
				statement = connection.createStatement();
				logger.info("Connessione al database effettuata");
				statement.executeUpdate("INSERT INTO farmer VALUES('"+farmer.getImei()+"','"+farmer.getLatitude()+"','"+farmer.getLongitude()+"','"+farmer.getAltitude()+"')");
				logger.info("Memorizzato nel database");
				outStream.writeInt(1);
				outStream.flush();
				logger.info("Abilitazione inviata e chiusura connessione");
				outStream.close();
				*/
				
				connection.close();
				statement.close();
				inStream.close();
				socket.close();
			} 
			catch (IOException e) 
			{
				e.printStackTrace();
			} 
			catch (ClassNotFoundException e) 
			{
				e.printStackTrace();
			} 
			catch (SQLException e) 
			{
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}
	
}
